package com.pachiraframework.springcloud.eureka.util;

import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;

/**
 * excel导出工具类
 */
public class ExcelExport {

    /**
     * @param response
     * @param title ：标题
     * @param name ：名字
     * @param list ：数据
     * @return
     */
    public static boolean exportExcel(HttpServletResponse response, String title, List<String> name ,List<List<String>> list) {

        try {
            OutputStream os = response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            response.setHeader("Content-disposition", "attachment; filename=file.xls");// 设定输出文件头
            response.setContentType("application/msexcel");// 定义输出类型

            WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件
            String tmptitle = title; // 标题
            WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称

            // 设置excel标题
            WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD,
                    false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            WritableCellFormat wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBackground(Colour.AQUA);
            wsheet.addCell(new Label(1, 0, tmptitle, wcfFC));
            wfont = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD,
                    false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            //标题
            for (int i = 0; i < name.size(); i++) {
                wsheet.addCell(new Label(i, 2, name.get(i)));
            }
            //数据
            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < list.get(i).size(); j++) {
                    wsheet.addCell(new Label(j, i + 3, list.get(i).get(j)));
                }
            }
            // 主体内容生成结束
            wbook.write(); // 写入文件
            wbook.close();
            os.close(); // 关闭流
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
